\ProvidesPackage{mylatex}[2023-9-20 mylatex]
\RequirePackage[outputdir=./latex-output]{minted}
\RequirePackage[margin=1in]{geometry}
\RequirePackage{expl3}
\RequirePackage{environ}
\RequirePackage{pdfpages}
\RequirePackage{iftex}
\RequirePackage{amsthm} % proof环境
\RequirePackage{fp}
\RequirePackage{color} % questionandanswer中的shaded

% TODO: 如果没有大量在公式中插入中文的需求也许可以不用这个了？
\ExplSyntaxOn
\NewEnviron{zhongwen}{
    \str_set:NV \temp {\BODY}
    \regex_replace_all:nnN{[^\x00-\xff]+}{\\textit\{\0\}}{\temp}
    % 应该可以使用\ifwindows和\iflinux来判断临时文件目录从而把临时文件放到临时文件目录里的
    \immediate\openout0=\jobname.zhongwen
    \immediate\write0{\temp}
    \immediate\closeout0
    \ExplSyntaxOff
    \input{\jobname.zhongwen}
    \ExplSyntaxOn
    % 好像没法删除临时文件，编译时会提示 rm: cannot remove '第十周作业.zhongwen': No such file or directory 但不影响编译，那还不如不删除了，少执行一个命令还能再快一点
    % \DeleteFile{\jobname.zhongwen}
}
\ExplSyntaxOff

% 这个使用会报错，暂时未修复：\begin{zhongwen} on input line 117 ended by \end{ChineseProof}.
\newenvironment{ChineseProof}{
    \begin{proof}
    \begin{zhongwen}
}{
    \end{zhongwen}
    \end{proof}
}

% https://castel.dev/post/lecture-notes-2/#
\newcommand{\incfig}[1]{%
    \def\svgwidth{\linewidth}
    {\fontsize{16pt}{0}
        \import{./latex-output/svg-inkscape-output/}{#1.pdf_tex}
    }
}

% minted
\ifwindows
  \providecommand{\DelayedDeleteFile}[2][]{%
    \ifthenelse{\equal{#1}{}}%
      {\IfFileExists{#2}{\DelayedShellEscape{del #2}}{}}%
      {\IfFileExists{#1/#2}{%
        \StrSubstitute{#1}{/}{\@backslashchar}[\minted@windir]
        \DelayedShellEscape{del \minted@windir\@backslashchar #2}}{}}}
\else
  \providecommand{\DelayedDeleteFile}[2][]{%
    \ifthenelse{\equal{#1}{}}%
      {\IfFileExists{#2}{\DelayedShellEscape{rm #2}}{}}%
      {\IfFileExists{#1/#2}{\DelayedShellEscape{rm #1/#2}}{}}}
\fi

% https://mirrors.pku.edu.cn/ctan/info/svg-inkscape/InkscapePDFLaTeX.pdf
% 这个只有PDFLaTeX才能用，filemod也是
\newcommand{\executeiffilenewer}[3]{%
    \ifnum\pdfstrcmp{\pdffilemoddate{#1}}%
    {\pdffilemoddate{#2}}>0%
    {\immediate\write18{#3}}\fi%
}

\newcommand{\includesvg}[1]{%
    \executeiffilenewer{./svg-inkscape/#1.svg}{./latex-output/svg-inkscape-output/#1.pdf}%
    {inkscape ./svg-inkscape/#1.svg %
    -o ./latex-output/svg-inkscape-output/#1.pdf --export-latex}%
    \incfig{#1}%
    % 好像不用删
    % \DelayedDeleteFile[svg-inkscape]{#1.pdf}
    % \DelayedDeleteFile[svg-inkscape]{#1.pdf_tex}
}

\newcommand{\includesvgpdf}[2][1]{%
    \executeiffilenewer{./svg-inkscape/#2.svg}{./latex-output/svg-inkscape-output/#2.pdf}%
    {inkscape ./svg-inkscape/#2.svg %
    -o ./latex-output/svg-inkscape-output/#2.pdf}%
    % \def\svgwidth{\linewidth}
    % {\fontsize{16pt}{0}
        \includegraphics[width=#1\linewidth]{./latex-output/svg-inkscape-output/#2.pdf}
    % }
    % 好像不用删
    % \DelayedDeleteFile[svg-inkscape]{#2.pdf}
    % \DelayedDeleteFile[svg-inkscape]{#2.pdf_tex}
}

% 就为了加个\noindent，但是没有装饰器，也没有继承，只能把原来的函数复制一份
% TODO: 试试expl3中有没有类似装饰器和继承的写法
\newcommand{\includexopp}[2][1]{
    \ProvideDirectory{./latex-output/xournalpp-output}
    \executeiffilenewer{./xournalpp/#2.xopp}{./latex-output/xournalpp-output/#2.pdf}%
    {xournalpp -p ./latex-output/xournalpp-output/#2.pdf ./xournalpp/#2.xopp && pdfcrop ./latex-output/xournalpp-output/#2.pdf ./latex-output/xournalpp-output/#2.pdf}

    \FPset\originwidth{#1}
    \FPset\one{1} 
    
    \FPiflt\originwidth\one
       \noindent\includegraphics[width=#1\linewidth]{./latex-output/xournalpp-output/#2.pdf}
    \else
        \FPdiv\targetwidth\one\originwidth
        \begin{center}
            \noindent\includegraphics[width=\FPprint\targetwidth\linewidth]{./latex-output/xournalpp-output/#2.pdf}
        \end{center}
    \fi
}

% https://zhuanlan.zhihu.com/p/144087254
\makeatletter
\@ifpackageloaded{amsthm}{
    \renewenvironment{proof}[1][\proofname]{\par
    \pushQED{\qed}%
    \normalfont \topsep6\p@\@plus6\p@\relax
    \trivlist
    \item[\hskip\labelsep
            \itshape
        #1\@addpunct{}]:\ignorespaces
    }{%
    \popQED\endtrivlist\@endpefalse
    }
}{}
\makeatother

% https://yangyq.net/2022/09/latex-overline-bar.html
\makeatletter
\newsavebox\myboxA
\newsavebox\myboxB
\newlength\mylenA
\newcommand*\xoverline[2][0.75]{%
\sbox{\myboxA}{$\m@th#2$}%
\setbox\myboxB\null% Phantom box
\ht\myboxB=\ht\myboxA%
\dp\myboxB=\dp\myboxA%
\wd\myboxB=#1\wd\myboxA% Scale phantom
\sbox\myboxB{$\m@th\,\overline{\copy\myboxB}\,$}% Overlined phantom
\setlength\mylenA{\the\wd\myboxA}% calc width diff
\addtolength\mylenA{-\the\wd\myboxB}%
\ifdim\wd\myboxB<\wd\myboxA%
\rlap{\hskip 0.5\mylenA\usebox\myboxB}{\usebox\myboxA}%
\else
\hskip -0.5\mylenA\rlap{\usebox\myboxA}{\hskip 0.5\mylenA\usebox\myboxB}%
\fi}
\makeatother


% my customed
\ifPDFTeX
    \RequirePackage{transparent}
\else
    \newcommand{\transparent}[1]{} % XeLaTeX不支持\transparent，LuaTeX没试过，还不确定\transparent可以接收几个参数，应该是只有一个
\fi

% \def\myitem#1#2{
%     \item \textbf{#1}
%     \begin{enumerate}
%         #2
%     \end{enumerate}
% }


% 这样的方式就能在列表项中用换段了
\newcommand{\myitem}[3][]{
    \IfBlankF{#1}{
        \setcounter{\getenum}{#1-1}
    }
    \item \textbf{#2}
    \begin{enumerate}[listparindent=\parindent]
        #3
    \end{enumerate}
}

\newcommand{\mycircle}[1]{\large{\textcircled{\normalsize#1}}\normalsize}

% 有\EnumitemId了
% 百分号要记得在判断语句的外面也用上
% 为了获取列表的深度容易吗，找了半天都找不到对应的命令，最后还得看enumitem的源码。在第1822行开始的部分找到了\@enumdepth和\@itemdepth，结合第933行的\number终于成功了。
\makeatletter
\def\getenum{%
    \ifnum\number\@enumdepth=1%
        enumi%
    \else
        \ifnum\number\@enumdepth=2%
            enumii%
        \else
            \ifnum\number\@enumdepth=3%
                enumiii%
            \else%
                enumiv%
            \fi
        \fi
    \fi%
}
\makeatother

\newcommand{\cnitem}[1][]{
    \IfBlankF{#1}{
        \setcounter{\getenum}{#1-1}
    }
    \item 
}


% 好像直接\AddEnumerateCounter就行

\ExplSyntaxOn
\newcommand{\ifnumerals}[3]{
    %  $, \Z or \z End of the subject token list.
    % 由于在正则表达式中的$符号仍然会被VSCode认为是数学环境
    % 虽然能编译成功，但是高亮看着很难受，所以使用了\z
    \regex_match:nnTF {^[0-9]*\z}{#1}{#2}{#3}
}
\ExplSyntaxOff

\newcommand{\questionandanswer}[3][]{%
    \begin{shaded}%
        \ifstrequal{#1}{-}{}{\ifnumerals{#1}{\cnitem[#1]}{\item[\textbf{#1}]}} #2%
    \end{shaded}%
    \begin{zhongwen}%
        #3%
    \end{zhongwen}%
}


% proof是名词，应该也用名词的solution而不是字母个数相等的solve
\newenvironment{solution}{
    \begin{proof}[解]
}{
    \end{proof}
}

% 待解决：有的的题目序号是“补”，可能无法使用cnitem
\ExplSyntaxOn
\cs_set:Nn \rawquestionandanswer:Nnnn {%
    \begin{shaded}%
        \ifstrequal{#2}{-}{}{\cnitem[#2]} #3%
    \end{shaded}%
    \begin{zhongwen}
        \begin{#1}% 不知道为什么这里即使去掉%也无法通过空行来换行所以只能用\\par了
            \par
            #4%
        \end{#1}%
    \end{zhongwen}
}

\newcommand{\questionandanswerProof}[3][]{%
    \rawquestionandanswer:Nnnn {proof} {#1}{#2}{#3}
}
\newcommand{\questionandanswerSolution}[3][]{%
    \rawquestionandanswer:Nnnn {solution} {#1}{#2}{#3}
}

\ExplSyntaxOff
% 成功实现了，而且下划线也没问题！！！似乎是函数式程序设计，或者装饰器模式？

% 由于minted用了verbatim，而verbatim的文档中有这样一句话：
% You cannot use the verbatim environment inside user defined commands;
% 可以看到在自己定义的环境里无法使用minted了。
